import exception.BusinessException;
import model.Item;
import model.ItemType;
import model.Order;
import repository.MemoryOrderRepository;
import repository.OrderRepository;
import service.OrderService;
import service.SimpleOrderService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {
    
    private static final OrderRepository repository = new MemoryOrderRepository();
    private static final OrderService orderService = new SimpleOrderService(repository);
    
    // 商品列表
    private static final Item hamburger = new Item("H001", "汉堡", 15.0, ItemType.MAIN);
    private static final Item fries = new Item("F002", "薯条", 15.0, ItemType.MAIN);
    private static final Item chickenWrap = new Item("W003", "鸡肉卷", 12.0, ItemType.MAIN);
    private static final Item icedCoffee = new Item("C004", "冰咖啡", 10.0, ItemType.DRINK);
    private static final Item cola = new Item("C005", "可乐", 8.0, ItemType.DRINK);
    private static final Item orangeJuice = new Item("J006", "橙汁", 9.0, ItemType.DRINK);
    private static final Item iceCream = new Item("D007", "冰淇淋", 6.0, ItemType.DESSERT);
    private static final Item cake = new Item("D008", "蛋糕", 12.0, ItemType.DESSERT);
    
    public static void main(String[] args) {
        System.out.println("===== 欢迎使用快餐店订单系统 =====");
        
        Scanner scanner = new Scanner(System.in);
        boolean running = true;
        
        while (running) {
            System.out.println("\n请选择操作：");
            System.out.println("1. 创建新订单");
            System.out.println("2. 展示所有示例场景");
            System.out.println("3. 退出");
            
            int choice = getIntInput(scanner, "请输入选项: ", 1, 3);
            
            switch (choice) {
                case 1:
                    createNewOrder(scanner);
                    break;
                case 2:
                    showAllExampleScenarios();
                    break;
                case 3:
                    running = false;
                    System.out.println("感谢使用，再见！");
                    break;
            }
        }
        
        scanner.close();
    }
    
    /**
     * 创建新订单交互
     */
    private static void createNewOrder(Scanner scanner) {
        System.out.println("\n===== 创建新订单 =====");
        System.out.println("可用商品列表：");
        System.out.println("1. 汉堡 (¥15.0)");
        System.out.println("2. 薯条 (¥15.0)");
        System.out.println("3. 鸡肉卷 (¥12.0)");
        System.out.println("4. 冰咖啡 (¥10.0)");
        System.out.println("5. 可乐 (¥8.0)");
        System.out.println("6. 橙汁 (¥9.0)");
        System.out.println("7. 冰淇淋 (¥6.0)");
        System.out.println("8. 蛋糕 (¥12.0)");
        
        List<Item> items = Arrays.asList(hamburger, fries, chickenWrap, icedCoffee, cola, orangeJuice, iceCream, cake);
        List<Item> selectedItems = Arrays.asList(new Item[5]); // 最多5个商品
        int itemCount = 0;
        
        boolean selecting = true;
        while (selecting && itemCount < 5) {
            int itemChoice = getIntInput(scanner, "请选择商品编号(1-8)，或输入0完成选择: ", 0, 8);
            
            if (itemChoice == 0) {
                selecting = false;
            } else {
                Item selectedItem = items.get(itemChoice - 1);
                // 复制一个新Item对象，避免引用原始对象
                Item itemCopy = new Item(
                    selectedItem.getId(),
                    selectedItem.getName(),
                    selectedItem.getPrice(),
                    selectedItem.getType()
                );
                selectedItems.set(itemCount, itemCopy);
                itemCount++;
                System.out.println("已添加: " + selectedItem.getName());
                
                if (itemCount >= 5) {
                    System.out.println("购物篮已满！");
                    selecting = false;
                }
            }
        }
        
        // 移除null元素
        List<Item> orderItems = selectedItems.subList(0, itemCount);
        
        if (orderItems.isEmpty()) {
            System.out.println("订单为空，取消创建！");
            return;
        }
        
        // 是否VIP
        boolean isVIP = getBooleanInput(scanner, "是否为VIP用户(y/n): ");
        
        // 创建订单
        try {
            Order order = orderService.createOrder(orderItems, isVIP);
            System.out.println("\n===== 订单创建成功 =====");
            printOrder(order);
        } catch (BusinessException e) {
            System.out.println("\n创建订单失败: " + e.getMessage());
            System.out.println("错误代码: " + e.getErrorCode());
        }
    }
    
    /**
     * 显示所有示例场景
     */
    private static void showAllExampleScenarios() {
        System.out.println("\n===== 示例场景展示 =====");
        
        // 场景1：基础校验 - 甜品单独购买
        System.out.println("\n场景1：基础校验 - 甜品单独购买");
        try {
            Order order = orderService.createOrder(Arrays.asList(iceCream), false);
            printOrder(order);
        } catch (BusinessException e) {
            System.out.println("预期异常: " + e.getMessage());
            System.out.println("错误代码: " + e.getErrorCode());
        }
        
        // 场景2：套餐组合优惠
        System.out.println("\n场景2：套餐组合优惠 - 汉堡+薯条=25元");
        try {
            Order order = orderService.createOrder(Arrays.asList(hamburger, fries), false);
            printOrder(order);
        } catch (BusinessException e) {
            System.out.println("异常: " + e.getMessage());
        }
        
        // 场景3：时间敏感规则 - 冰咖啡下午3点后不售卖
        System.out.println("\n场景3：时间敏感规则 - 冰咖啡下午3点后不售卖");
        try {
            // 模拟下午4点
            LocalDateTime time = LocalDateTime.now().withHour(16).withMinute(0);
            Order order = orderService.createOrder(Arrays.asList(hamburger, icedCoffee), false, time);
            printOrder(order);
        } catch (BusinessException e) {
            System.out.println("异常: " + e.getMessage());
        }
        
        // 场景4：VIP折扣
        System.out.println("\n场景4：VIP折扣 - 9折优惠");
        try {
            Order order = orderService.createOrder(Arrays.asList(hamburger, cake), true);
            printOrder(order);
        } catch (BusinessException e) {
            System.out.println("异常: " + e.getMessage());
        }
        
        // 场景5：第二杯半价
        System.out.println("\n场景5：第二杯半价 - 相同饮料第二杯半价");
        try {
            Item cola1 = new Item(cola.getId(), cola.getName(), cola.getPrice(), cola.getType());
            Item cola2 = new Item(cola.getId(), cola.getName(), cola.getPrice(), cola.getType());
            Order order = orderService.createOrder(Arrays.asList(hamburger, cola1, cola2), false);
            printOrder(order);
        } catch (BusinessException e) {
            System.out.println("异常: " + e.getMessage());
        }
        
        // 场景6：商品数量超限
        System.out.println("\n场景6：商品数量超限 - 单笔订单最多5个商品");
        try {
            Order order = orderService.createOrder(
                Arrays.asList(hamburger, fries, chickenWrap, cola, orangeJuice, iceCream), 
                false
            );
            printOrder(order);
        } catch (BusinessException e) {
            System.out.println("预期异常: " + e.getMessage());
            System.out.println("错误代码: " + e.getErrorCode());
        }
        
        // 场景7：订单取消
        System.out.println("\n场景7：订单取消");
        try {
            // 创建订单
            Order order = orderService.createOrder(Arrays.asList(hamburger), false);
            System.out.println("订单创建成功，ID: " + order.getOrderId());
            
            // 取消订单
            orderService.cancelOrder(order.getOrderId());
            
            // 查询取消后的订单
            Order cancelledOrder = repository.findById(order.getOrderId());
            System.out.println("订单状态: " + cancelledOrder.getStatus());
            System.out.println("订单备注: " + cancelledOrder.getRemarks());
        } catch (BusinessException e) {
            System.out.println("异常: " + e.getMessage());
        }
        
        // 场景8：订单超时自动取消
        System.out.println("\n场景8：订单超时自动取消");
        try {
            // 创建订单（模拟10:00创建）
            LocalDateTime createTime = LocalDateTime.now().withHour(10).withMinute(0);
            Order order = orderService.createOrder(Arrays.asList(hamburger), false, createTime);
            System.out.println("订单创建成功，ID: " + order.getOrderId() + "，创建时间: " + formatDateTime(createTime));
            
            // 模拟31分钟后查询
            LocalDateTime checkTime = createTime.plusMinutes(31);
            System.out.println("31分钟后查询订单（" + formatDateTime(checkTime) + "）");
            
            // 查询订单（触发自动取消检查）
            orderService.cancelOrder(order.getOrderId(), checkTime);
            
            // 查询取消后的订单
            Order cancelledOrder = repository.findById(order.getOrderId());
            System.out.println("订单状态: " + cancelledOrder.getStatus());
            System.out.println("订单备注: " + cancelledOrder.getRemarks());
        } catch (BusinessException e) {
            System.out.println("异常: " + e.getMessage());
        }
    }
    
    /**
     * 打印订单详情
     */
    private static void printOrder(Order order) {
        System.out.println("订单ID: " + order.getOrderId());
        System.out.println("创建时间: " + formatDateTime(order.getCreateTime()));
        System.out.println("状态: " + order.getStatus());
        System.out.println("商品列表:");
        
        for (Item item : order.getItems()) {
            System.out.println("  - " + item.getName() + " (¥" + item.getPrice() + ")");
        }
        
        System.out.println("总价: ¥" + order.getTotalPrice());
        
        if (!order.getRemarks().isEmpty()) {
            System.out.println("备注:");
            for (String remark : order.getRemarks()) {
                System.out.println("  - " + remark);
            }
        }
    }
    
    /**
     * 获取整数输入
     */
    private static int getIntInput(Scanner scanner, String prompt, int min, int max) {
        int input;
        while (true) {
            System.out.print(prompt);
            try {
                input = Integer.parseInt(scanner.nextLine().trim());
                if (input >= min && input <= max) {
                    return input;
                } else {
                    System.out.println("请输入" + min + "到" + max + "之间的数字！");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字！");
            }
        }
    }
    
    /**
     * 获取布尔输入
     */
    private static boolean getBooleanInput(Scanner scanner, String prompt) {
        while (true) {
            System.out.print(prompt);
            String input = scanner.nextLine().trim().toLowerCase();
            if (input.equals("y") || input.equals("yes")) {
                return true;
            } else if (input.equals("n") || input.equals("no")) {
                return false;
            } else {
                System.out.println("请输入 y/yes 或 n/no！");
            }
        }
    }
    
    /**
     * 格式化日期时间
     */
    private static String formatDateTime(LocalDateTime dateTime) {
        return dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
} 